library(effects)
library(jtools)
library(stargazer)
library(dotwhisker)
library(ggplot2)
library(weights)
library(AER)
library(gridExtra)
library(ggpubr)
library(formattable)
library(interactions)
library(reshape)
library(dplyr)
library(tidyr)
library(htmlwidgets)
library(grid)

MOC <- function (data, its, model, prog.int=100, rsq=TRUE) {
  ## Method of Composition (Caughey and Warshaw, 2018; Treier and Jackman, 2008)
  tildeB <- as.data.frame(matrix(nrow=length(its), ncol=length(coef(model))))
  R2 <- data.frame(rsq=rep(NA, length(its)), adjrsq=rep(NA, length(its)))
  for (s in seq_along(its)) {
    if (!s %% prog.int) print(s)
    it <- its[s]
    ## (1) Sample from p(x)
    data_s <- subset(data, It == it)
    #names(data_s) <- gsub("\\_s$", "\\_mean", names(data_s)) 
    ## (2) Sample from p(B|x,y):
    ##     (a) Estimate B_s and Cov(B_s) conditional on x_s.
    mod_s <- update(model, data=data_s)
    hatB_s <- coef(mod_s)
    hatV_s <- vcov(mod_s)
    ##     (b) Sample \tilde{B_s} from MV(\hat{B_s}, \hat{Cov(B_s)}).
    tildeB[s, ] <- MASS::mvrnorm(n = 1, mu = hatB_s, Sigma = hatV_s)
    if (rsq) {
      R2$rsq[s] <- summary(mod_s)$r.squared["rsq"]
      R2$adjrsq[s] <- summary(mod_s)$r.squared["adjrsq"]
    }
  }
  names(tildeB) <- names(coef(model))
  if (rsq) {
    tildeB$rsq <- R2$rsq
    tildeB$adjrsq <- R2$adjrsq
  }
  return(tildeB)
}

##### ANALYSIS

dataend2 <- read.csv("replicationdatapoqfinal.csv")
  
# Table A.5

meancovs <- round(apply(dataend2[,c("allidealMCMCmean","mrp_mean",
                                    "genelection","prioryears","termlimit","fouryeartermactual",
                                    "Republican")],2,mean,na.rm=T),3)
mincovs <- round(apply(dataend2[,c("allidealMCMCmean","mrp_mean",
                                   "genelection","prioryears","termlimit","fouryeartermactual",
                                   "Republican")],2,min,na.rm=T),3)
maxcovs <- round(apply(dataend2[,c("allidealMCMCmean","mrp_mean",
                                   "genelection","prioryears","termlimit","fouryeartermactual",
                                   "Republican")],2,max,na.rm=T),3)
medcovs <- round(apply(dataend2[,c("allidealMCMCmean","mrp_mean",
                                   "genelection","prioryears","termlimit","fouryeartermactual",
                                   "Republican")],2,quantile,0.5,na.rm=T),3)
varnames <- c("Legislator Ideal Point","Constituency Ideal Point",
              "Number of General Elections","Length of Tenure","Term-Limit Status",
              "Number of Four-Year Terms","Republican")

sumstattable <- data.frame(cbind(varnames,meancovs,medcovs,mincovs,maxcovs))
colnames(sumstattable) <- c("Variable Name","Mean","Median","Minimum","Maximum")
rownames(sumstattable) <- NULL


Summarytable <- formattable(sumstattable, 
                            align =c("l","c","c","c","c"), 
                            list(`Variable Name` = formatter(
                              "span", style = ~ style(color = "grey",font.weight = "bold")) 
                            ))
png("TableA5.png")
Summarytable
dev.off()

# Figure A.8

regbalance <- lm(treattwo~np_score+mrp_mean+PercentMargin+
                   genelection+prioryears+fouryeartermactual+
                   Republican,data=dataend2) 

term <- c("Shor and McCarty Score", "Constituency Ideal Point", 
          "Vote Margin","Number of General Elections","Prior Years Served",
          "Republican")
estimate <- c(regbalance$coefficients["np_score"],regbalance$coefficients["mrp_mean"],
              regbalance$coefficients["PercentMargin"],regbalance$coefficients["genelection"],
              regbalance$coefficients["prioryears"],regbalance$coefficients["Republican"])
std.error <- c(summary(regbalance)$coefficients["np_score",2],
               summary(regbalance)$coefficients["mrp_mean",2],
               summary(regbalance)$coefficients["PercentMargin",2],
               summary(regbalance)$coefficients["genelection",2],
               summary(regbalance)$coefficients["prioryears",2],
               summary(regbalance)$coefficients["Republican",2])
pvalues <- c(summary(regbalance)$coefficients["np_score","Pr(>|t|)"],
             summary(regbalance)$coefficients["mrp_mean","Pr(>|t|)"],
             summary(regbalance)$coefficients["PercentMargin","Pr(>|t|)"],
             summary(regbalance)$coefficients["genelection","Pr(>|t|)"],
             summary(regbalance)$coefficients["prioryears","Pr(>|t|)"],
             summary(regbalance)$coefficients["Republican","Pr(>|t|)"])
pvalues <- round(pvalues,3)
pvalues <- ifelse(pvalues==0,paste("p < 0.001"),paste("p=",pvalues,sep=""))
dfplot <- data.frame(term, estimate, std.error)
png("FigureA8.png",width=1400,res=250,height=750)
dwplot(dfplot) +
  geom_vline(aes(x=0), lty=2, xintercept=0) +
  theme_bw()+
  ylab('Variable') + 
  xlab('Coefficient') +
  xlim(c(-0.6,0.5)) +
  scale_y_discrete(name = 'Variable',label=c('Republican',
                                             'Length of Tenure', 'Number of General Elections',
                                             'Electoral Margin',
                                             'Constituency Ideal Point',
                                             'Legislator Ideal Point')) +
  geom_text(x=0.45,y=1,label=paste(pvalues[6],sep=""),fontface=6)+
  geom_text(x=0.45,y=2,label=paste(pvalues[5],sep=""),fontface=6)+
  geom_text(x=0.45,y=3,label=paste(pvalues[4],sep=""),fontface=6)+
  geom_text(x=0.45,y=4,label=paste(pvalues[3],sep=""),fontface=6)+
  geom_text(x=0.45,y=5,label=paste(pvalues[2],sep=""),fontface=6)+
  geom_text(x=0.45,y=6,label=paste(pvalues[1],sep=""),fontface=6)+
  theme(plot.title = element_text(face="bold",hjust=0.5),
        legend.position = "none")
dev.off()

# Figure B.9

AReconreg <- lm(econidealMCMCmean~econmrpMCMCmean,data=dataend2[dataend2$StateAbbr=="AR",])
theme_set(theme_bw())
ARplot <- ggplot(dataend2[dataend2$StateAbbr=="AR",], aes(x=econmrpMCMCmean, y=econidealMCMCmean,color=as.factor(1 - Republican),
                                                          shape=as.factor(Republican+1))) + 
  geom_point() +
  geom_abline(intercept=AReconreg$coefficients["(Intercept)"],slope=AReconreg$coefficients["econmrpMCMCmean"],
              col="gray",lwd=1) + 
  xlim(c(-1,1))+
  ylim(c(-2,2))+
  labs(y="Legislator Ideal Point", 
       x="Constituency Ideal Point") + 
  ggtitle("Arkansas") +
  scale_color_discrete(name = "",
                       breaks=c("1","0"),
                       labels=c("Democrat","Republican")) + 
  scale_shape_discrete(name  ="",
                       breaks=c("1","2"),
                       labels=c("Democrat", "Republican")) +
  theme(plot.title = element_text(hjust = 0.5)) + 
  theme(legend.position="bottom")
ILeconreg <- lm(econidealMCMCmean~econmrpMCMCmean,data=dataend2[dataend2$StateAbbr=="IL",])
ILplot <- ggplot(dataend2[dataend2$StateAbbr=="IL",], aes(x=econmrpMCMCmean, y=econidealMCMCmean,color=as.factor(1 - Republican),
                                                          shape=as.factor(Republican+1))) + 
  geom_point() +
  xlim(c(-1,1))+
  ylim(c(-2,2))+
  geom_abline(intercept=ILeconreg$coefficients["(Intercept)"],slope=ILeconreg$coefficients["econmrpMCMCmean"],
              col="gray",lwd=1) + 
  labs(y="Legislator Ideal Point", 
       x="Constituency Ideal Point") + 
  ggtitle("Illinois") +
  scale_color_discrete(name = "",
                       breaks=c("1","0"),
                       labels=c("Democrat","Republican")) + 
  scale_shape_discrete(name  ="",
                       breaks=c("1","2"),
                       labels=c("Democrat", "Republican")) +
  theme(plot.title = element_text(hjust = 0.5))
FLeconreg <- lm(econidealMCMCmean~econmrpMCMCmean,data=dataend2[dataend2$StateAbbr=="FL",])
FLplot <- ggplot(dataend2[dataend2$StateAbbr=="FL",], aes(x=econmrpMCMCmean, y=econidealMCMCmean,color=as.factor(1 - Republican),
                                                          shape=as.factor(Republican+1))) + 
  geom_point() +
  xlim(c(-1,1))+
  ylim(c(-2,2))+
  geom_abline(intercept=FLeconreg$coefficients["(Intercept)"],slope=FLeconreg$coefficients["econmrpMCMCmean"],
              col="gray",lwd=1) + 
  labs(y="Legislator Ideal Point", 
       x="Constituency Ideal Point") + 
  scale_color_discrete(name = "",
                       breaks=c("1","0"),
                       labels=c("Democrat","Republican")) + 
  scale_shape_discrete(name  ="",
                       breaks=c("1","2"),
                       labels=c("Democrat", "Republican")) +
  ggtitle("Florida") +
  theme(plot.title = element_text(hjust = 0.5))
TXeconreg <- lm(econidealMCMCmean~econmrpMCMCmean,data=dataend2[dataend2$StateAbbr=="TX",])
TXplot <- ggplot(dataend2[dataend2$StateAbbr=="TX",], aes(x=econmrpMCMCmean, y=econidealMCMCmean,color=as.factor(1 - Republican),
                                                          shape=as.factor(Republican+1))) + 
  geom_point()+
  xlim(c(-1,1))+
  ylim(c(-2,2))+
  geom_abline(intercept=TXeconreg$coefficients["(Intercept)"],slope=TXeconreg$coefficients["econmrpMCMCmean"],
              col="gray",lwd=1) + 
  labs(y="Legislator Ideal Point", 
       x="Constituency Ideal Point")+ 
  scale_color_discrete(name = "",
                       breaks=c("1","0"),
                       labels=c("Democrat","Republican")) + 
  scale_shape_discrete(name  ="",
                       breaks=c("1","2"),
                       labels=c("Democrat", "Republican")) +
  ggtitle("Texas") +
  theme(plot.title = element_text(hjust = 0.5))

g_legend<-function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)}
mylegend <- g_legend(ARplot)
png("FigureB9.png",width=1400,res=250,height=1000)
grid.arrange(arrangeGrob(ARplot + theme(legend.position="none"),
                         FLplot + theme(legend.position="none"),
                         ILplot + theme(legend.position="none"),
                         TXplot + theme(legend.position="none"),
                         nrow=2,ncol=2),
             mylegend, nrow=2,heights=c(10, 1))
dev.off()


# Figure B.10

ARcrimreg <- lm(crimidealMCMCmean~crimmrpMCMCmean,data=dataend2[dataend2$StateAbbr=="AR",])
theme_set(theme_bw())
ARplot <- ggplot(dataend2[dataend2$StateAbbr=="AR",], aes(x=crimmrpMCMCmean, y=crimidealMCMCmean,color=as.factor(1 - Republican),
                                                          shape=as.factor(Republican+1))) + 
  geom_point() +
  geom_abline(intercept=ARcrimreg$coefficients["(Intercept)"],slope=ARcrimreg$coefficients["crimmrpMCMCmean"],
              col="gray",lwd=1) + 
  xlim(c(-1,1))+
  ylim(c(-2,2))+
  labs(y="Legislator Ideal Point", 
       x="Constituency Ideal Point") + 
  ggtitle("Arkansas") +
  scale_color_discrete(name = "",
                       breaks=c("1","0"),
                       labels=c("Democrat","Republican")) + 
  scale_shape_discrete(name  ="",
                       breaks=c("1","2"),
                       labels=c("Democrat", "Republican")) +
  theme(plot.title = element_text(hjust = 0.5)) + 
  theme(legend.position="bottom")
ILcrimreg <- lm(crimidealMCMCmean~crimmrpMCMCmean,data=dataend2[dataend2$StateAbbr=="IL",])
ILplot <- ggplot(dataend2[dataend2$StateAbbr=="IL",], aes(x=crimmrpMCMCmean, y=crimidealMCMCmean,color=as.factor(1 - Republican),
                                                          shape=as.factor(Republican+1))) + 
  geom_point() +
  xlim(c(-1,1))+
  ylim(c(-2,2))+
  geom_abline(intercept=ILcrimreg$coefficients["(Intercept)"],slope=ILcrimreg$coefficients["crimmrpMCMCmean"],
              col="gray",lwd=1) + 
  labs(y="Legislator Ideal Point", 
       x="Constituency Ideal Point") + 
  ggtitle("Illinois") +
  scale_color_discrete(name = "",
                       breaks=c("1","0"),
                       labels=c("Democrat","Republican")) + 
  scale_shape_discrete(name  ="",
                       breaks=c("1","2"),
                       labels=c("Democrat", "Republican")) +
  theme(plot.title = element_text(hjust = 0.5))
FLcrimreg <- lm(crimidealMCMCmean~crimmrpMCMCmean,data=dataend2[dataend2$StateAbbr=="FL",])
FLplot <- ggplot(dataend2[dataend2$StateAbbr=="FL",], aes(x=crimmrpMCMCmean, y=crimidealMCMCmean,color=as.factor(1 - Republican),
                                                          shape=as.factor(Republican+1))) + 
  geom_point() +
  xlim(c(-1,1))+
  ylim(c(-2,2))+
  geom_abline(intercept=FLcrimreg$coefficients["(Intercept)"],slope=FLcrimreg$coefficients["crimmrpMCMCmean"],
              col="gray",lwd=1) + 
  labs(y="Legislator Ideal Point", 
       x="Constituency Ideal Point") + 
  scale_color_discrete(name = "",
                       breaks=c("1","0"),
                       labels=c("Democrat","Republican")) + 
  scale_shape_discrete(name  ="",
                       breaks=c("1","2"),
                       labels=c("Democrat", "Republican")) +
  ggtitle("Florida") +
  theme(plot.title = element_text(hjust = 0.5))
TXcrimreg <- lm(crimidealMCMCmean~crimmrpMCMCmean,data=dataend2[dataend2$StateAbbr=="TX",])
TXplot <- ggplot(dataend2[dataend2$StateAbbr=="TX",], aes(x=crimmrpMCMCmean, y=crimidealMCMCmean,color=as.factor(1 - Republican),
                                                          shape=as.factor(Republican+1))) + 
  geom_point()+
  xlim(c(-1,1))+
  ylim(c(-2,2))+
  geom_abline(intercept=TXcrimreg$coefficients["(Intercept)"],slope=TXcrimreg$coefficients["crimmrpMCMCmean"],
              col="gray",lwd=1) + 
  labs(y="Legislator Ideal Point", 
       x="Constituency Ideal Point")+ 
  scale_color_discrete(name = "",
                       breaks=c("1","0"),
                       labels=c("Democrat","Republican")) + 
  scale_shape_discrete(name  ="",
                       breaks=c("1","2"),
                       labels=c("Democrat", "Republican")) +
  ggtitle("Texas") +
  theme(plot.title = element_text(hjust = 0.5))

g_legend<-function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)}
mylegend <- g_legend(ARplot)
png("FigureB10.png",width=1400,res=250,height=1000)
grid.arrange(arrangeGrob(ARplot + theme(legend.position="none"),
                         FLplot + theme(legend.position="none"),
                         ILplot + theme(legend.position="none"),
                         TXplot + theme(legend.position="none"),
                         nrow=2,ncol=2),
             mylegend, nrow=2,heights=c(10, 1))
dev.off()

# Figure B.11

ARenvreg <- lm(envidealMCMCmean~envmrpMCMCmean,data=dataend2[dataend2$StateAbbr=="AR",])
theme_set(theme_bw())
ARplot <- ggplot(dataend2[dataend2$StateAbbr=="AR",], aes(x=envmrpMCMCmean, y=envidealMCMCmean,color=as.factor(1 - Republican),
                                                          shape=as.factor(Republican+1))) + 
  geom_point() +
  geom_abline(intercept=ARenvreg$coefficients["(Intercept)"],slope=ARenvreg$coefficients["envmrpMCMCmean"],
              col="gray",lwd=1) + 
  xlim(c(-1,1))+
  ylim(c(-2,2))+
  labs(y="Legislator Ideal Point", 
       x="Constituency Ideal Point") + 
  ggtitle("Arkansas") +
  scale_color_discrete(name = "",
                       breaks=c("1","0"),
                       labels=c("Democrat","Republican")) + 
  scale_shape_discrete(name  ="",
                       breaks=c("1","2"),
                       labels=c("Democrat", "Republican")) +
  theme(plot.title = element_text(hjust = 0.5)) + 
  theme(legend.position="bottom")
ILenvreg <- lm(envidealMCMCmean~envmrpMCMCmean,data=dataend2[dataend2$StateAbbr=="IL",])
ILplot <- ggplot(dataend2[dataend2$StateAbbr=="IL",], aes(x=envmrpMCMCmean, y=envidealMCMCmean,color=as.factor(1 - Republican),
                                                          shape=as.factor(Republican+1))) + 
  geom_point() +
  xlim(c(-1,1))+
  ylim(c(-2,2))+
  geom_abline(intercept=ILenvreg$coefficients["(Intercept)"],slope=ILenvreg$coefficients["envmrpMCMCmean"],
              col="gray",lwd=1) + 
  labs(y="Legislator Ideal Point", 
       x="Constituency Ideal Point") + 
  ggtitle("Illinois") +
  scale_color_discrete(name = "",
                       breaks=c("1","0"),
                       labels=c("Democrat","Republican")) + 
  scale_shape_discrete(name  ="",
                       breaks=c("1","2"),
                       labels=c("Democrat", "Republican")) +
  theme(plot.title = element_text(hjust = 0.5))
FLenvreg <- lm(envidealMCMCmean~envmrpMCMCmean,data=dataend2[dataend2$StateAbbr=="FL",])
FLplot <- ggplot(dataend2[dataend2$StateAbbr=="FL",], aes(x=envmrpMCMCmean, y=envidealMCMCmean,color=as.factor(1 - Republican),
                                                          shape=as.factor(Republican+1))) + 
  geom_point() +
  xlim(c(-1,1))+
  ylim(c(-2,2))+
  geom_abline(intercept=FLenvreg$coefficients["(Intercept)"],slope=FLenvreg$coefficients["envmrpMCMCmean"],
              col="gray",lwd=1) + 
  labs(y="Legislator Ideal Point", 
       x="Constituency Ideal Point") + 
  scale_color_discrete(name = "",
                       breaks=c("1","0"),
                       labels=c("Democrat","Republican")) + 
  scale_shape_discrete(name  ="",
                       breaks=c("1","2"),
                       labels=c("Democrat", "Republican")) +
  ggtitle("Florida") +
  theme(plot.title = element_text(hjust = 0.5))
TXenvreg <- lm(envidealMCMCmean~envmrpMCMCmean,data=dataend2[dataend2$StateAbbr=="TX",])
TXplot <- ggplot(dataend2[dataend2$StateAbbr=="TX",], aes(x=envmrpMCMCmean, y=envidealMCMCmean,color=as.factor(1 - Republican),
                                                          shape=as.factor(Republican+1))) + 
  geom_point()+
  xlim(c(-1,1))+
  ylim(c(-2,2))+
  geom_abline(intercept=TXenvreg$coefficients["(Intercept)"],slope=TXenvreg$coefficients["envmrpMCMCmean"],
              col="gray",lwd=1) + 
  labs(y="Legislator Ideal Point", 
       x="Constituency Ideal Point")+ 
  scale_color_discrete(name = "",
                       breaks=c("1","0"),
                       labels=c("Democrat","Republican")) + 
  scale_shape_discrete(name  ="",
                       breaks=c("1","2"),
                       labels=c("Democrat", "Republican")) +
  ggtitle("Texas") +
  theme(plot.title = element_text(hjust = 0.5))

g_legend<-function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)}
mylegend <- g_legend(ARplot)
png("FigureB11.png",width=1400,res=250,height=1000)
grid.arrange(arrangeGrob(ARplot + theme(legend.position="none"),
                         FLplot + theme(legend.position="none"),
                         ILplot + theme(legend.position="none"),
                         TXplot + theme(legend.position="none"),
                         nrow=2,ncol=2),
             mylegend, nrow=2,heights=c(10, 1))
dev.off()

# Figure B.12

allnp <- ggplot(dataend2, aes(x=np_score, y=allidealMCMCmean)) + 
  geom_point()+
  theme_bw()+
  xlim(c(-2,2))+
  ylim(c(-2,2))+
  ggtitle("All Votes")+
  geom_smooth(method = "lm", se = FALSE,fullrange=T,
              col="gray",lwd=1) + 
  labs(y="Roll Calls", 
       x="Shor and McCarty Score")+
  theme(plot.title = element_text(hjust = 0.5))
econnp <- ggplot(dataend2, aes(x=np_score, y=econidealMCMCmean)) + 
  geom_point()+
  theme_bw()+
  xlim(c(-2,2))+
  ylim(c(-2,2))+
  ggtitle("Economic")+
  geom_smooth(method = "lm", se = FALSE,fullrange=T,
              col="gray",lwd=1) + 
  labs(y="Roll Calls", 
       x="Shor and McCarty Score")+
  theme(plot.title = element_text(hjust = 0.5))
envnp <- ggplot(dataend2, aes(x=np_score, y=envidealMCMCmean)) + 
  geom_point()+
  theme_bw()+
  xlim(c(-2,2))+
  ylim(c(-2,2))+
  ggtitle("Environment")+
  geom_smooth(method = "lm", se = FALSE,fullrange=T,
              col="gray",lwd=1) + 
  labs(y="Roll Calls", 
       x="Shor and McCarty Score")+
  theme(plot.title = element_text(hjust = 0.5))
crimnp <- ggplot(dataend2, aes(x=np_score, y=crimidealMCMCmean)) + 
  geom_point()+
  theme_bw()+
  xlim(c(-2,2))+
  ylim(c(-2,2))+
  ggtitle("Crime")+
  geom_smooth(method = "lm", se = FALSE,fullrange=T,
              col="gray",lwd=1) + 
  labs(y="Roll Calls", 
       x="Shor and McCarty Score")+
  theme(plot.title = element_text(hjust = 0.5))
png("FigureB12.png",width=1400,res=250,height=1000)
ggarrange(allnp,econnp,envnp,crimnp,nrow=2,ncol=2,
          widths=c(1,1))
dev.off()

# Table C.6

allidealMCMC <- read.csv("allidealMCMC.csv") %>% select(num_range(prefix="X",range=1:500))
econidealMCMC <- read.csv("econidealMCMC.csv") %>% select(num_range(prefix="X",range=1:500))
envidealMCMC <- read.csv("envidealMCMC.csv") %>% select(num_range(prefix="X",range=1:500))
crimidealMCMC <- read.csv("crimidealMCMC.csv") %>% select(num_range(prefix="X",range=1:500))
allmrpMCMC <- read.csv("allmrpMCMC.csv") %>% select(num_range(prefix="X",range=1:500))
econmrpMCMC <- read.csv("econmrpMCMC.csv") %>% select(num_range(prefix="X",range=1:500))
envmrpMCMC <- read.csv("envmrpMCMC.csv") %>% select(num_range(prefix="X",range=1:500))
crimmrpMCMC <- read.csv("crimmrpMCMC.csv") %>% select(num_range(prefix="X",range=1:500))

alldataideal <- data.frame(cbind(dataend2,allidealMCMC)) %>% select(num_range(prefix="X",range=1:500),treattwo,Republican,StateAbbr,Session) %>%
  melt(id.vars=c("treattwo","Republican","StateAbbr","Session"))
alldatamrp <- data.frame(cbind(dataend2,allmrpMCMC)) %>% select(num_range(prefix="X",range=1:500),treattwo,Republican,StateAbbr,Session) %>%
  melt(id.vars=c("treattwo","Republican","StateAbbr","Session"))
alldata <- data.frame(cbind(alldataideal,alldatamrp[,"value"]))
colnames(alldata) <- c("treattwo","Republican","StateAbbr","Session",
                       "It","ideal","opinion")

econdataideal <- data.frame(cbind(dataend2,econidealMCMC)) %>% select(num_range(prefix="X",range=1:500),treattwo,Republican,StateAbbr,Session) %>%
  melt(id.vars=c("treattwo","Republican","StateAbbr","Session"))
econdatamrp <- data.frame(cbind(dataend2,econmrpMCMC)) %>% select(num_range(prefix="X",range=1:500),treattwo,Republican,StateAbbr,Session) %>%
  melt(id.vars=c("treattwo","Republican","StateAbbr","Session"))
econdata <- data.frame(cbind(econdataideal,econdatamrp[,"value"]))
colnames(econdata) <- c("treattwo","Republican","StateAbbr","Session",
                        "It","ideal","opinion")

envdataideal <- data.frame(cbind(dataend2,envidealMCMC)) %>% select(num_range(prefix="X",range=1:500),treattwo,Republican,StateAbbr,Session) %>%
  melt(id.vars=c("treattwo","Republican","StateAbbr","Session"))
envdatamrp <- data.frame(cbind(dataend2,envmrpMCMC)) %>% select(num_range(prefix="X",range=1:500),treattwo,Republican,StateAbbr,Session) %>%
  melt(id.vars=c("treattwo","Republican","StateAbbr","Session"))
envdata <- data.frame(cbind(envdataideal,envdatamrp[,"value"]))
colnames(envdata) <- c("treattwo","Republican","StateAbbr","Session",
                       "It","ideal","opinion")

crimdataideal <- data.frame(cbind(dataend2,crimidealMCMC)) %>% select(num_range(prefix="X",range=1:500),treattwo,Republican,StateAbbr,Session) %>%
  melt(id.vars=c("treattwo","Republican","StateAbbr","Session"))
crimdatamrp <- data.frame(cbind(dataend2,crimmrpMCMC)) %>% select(num_range(prefix="X",range=1:500),treattwo,Republican,StateAbbr,Session) %>%
  melt(id.vars=c("treattwo","Republican","StateAbbr","Session"))
crimdata <- data.frame(cbind(crimdataideal,crimdatamrp[,"value"]))
colnames(crimdata) <- c("treattwo","Republican","StateAbbr","Session",
                       "It","ideal","opinion")

alldata$It <- as.numeric(gsub("X","",alldata$It))
econdata$It <- as.numeric(gsub("X","",econdata$It))
envdata$It <- as.numeric(gsub("X","",envdata$It)) 
crimdata$It <- as.numeric(gsub("X","",crimdata$It))

its <- sort(sample(unique(alldata$It), min(500, length(unique(alldata$It)))))
ElectoralProx <- lm(ideal~opinion*treattwo+Republican+StateAbbr+as.factor(Session),data=alldata[alldata$It==1,])
ElectoralProxEcon <- lm(ideal~opinion*treattwo+Republican+StateAbbr+as.factor(Session),data=econdata[econdata$It==1,])
ElectoralProxEnv <- lm(ideal~opinion*treattwo+Republican+StateAbbr+as.factor(Session),data=envdata[envdata$It==1,])
ElectoralProxCrim <- lm(ideal~opinion*treattwo+Republican+StateAbbr+as.factor(Session),data=crimdata[crimdata$It==1,])
set.seed(401)
moc1 <- MOC(data=alldata,its=its,model=ElectoralProx,rsq=FALSE)
moc2 <- MOC(data=econdata,its=its,model=ElectoralProxEcon,rsq=FALSE)
moc3 <- MOC(data=envdata,its=its,model=ElectoralProxEnv,rsq=FALSE)
moc4 <- MOC(data=crimdata,its=its,model=ElectoralProxCrim,rsq=FALSE)

moc.est <- list(apply(moc1,2,mean,na.rm=T),apply(moc2,2,mean,na.rm=T),
                apply(moc3,2,mean,na.rm=T),apply(moc4,2,mean,na.rm=T))
moc.sd <- list(apply(moc1,2,sd,na.rm=T),apply(moc2,2,sd,na.rm=T),
               apply(moc3,2,sd,na.rm=T),apply(moc4,2,sd,na.rm=T))

stargazer(
  ElectoralProx,ElectoralProxEcon,ElectoralProxEnv,ElectoralProxCrim,
  font.size="footnotesize",model.numbers=F,
  column.sep.width="1pt",single.row=T,type="html",out="tableC6.htm",
  keep=c("opinion","treattwo","opinion:treattwo"),
  covariate.labels=c("Constituency Opinion","Two-Year","Const. Opinion * Two-Year"),
  coef=moc.est,se=moc.sd,p.auto=T,report=c("vcsp"),
  title="Electoral Proximity Effect (time period T)",
  dep.var.labels="Legislator Ideal Point",
  column.labels=c("All Votes","Economic","Environment","Crime"),
  omit.stat=c("F", "rsq","adj.rsq","ser")
)

## Table C.7

ElectoralProxNoCon <- lm(ideal~opinion*treattwo,data=alldata[alldata$It==1,])
ElectoralProxNoConEcon <- lm(ideal~opinion*treattwo,data=econdata[econdata$It==1,])
ElectoralProxNoConEnv <- lm(ideal~opinion*treattwo,data=envdata[envdata$It==1,])
ElectoralProxNoConCrim <- lm(ideal~opinion*treattwo,data=crimdata[crimdata$It==1,])
set.seed(401)
moc1 <- MOC(data=alldata,its=its,model=ElectoralProxNoCon,rsq=FALSE)
moc2 <- MOC(data=econdata,its=its,model=ElectoralProxNoConEcon,rsq=FALSE)
moc3 <- MOC(data=envdata,its=its,model=ElectoralProxNoConEnv,rsq=FALSE)
moc4 <- MOC(data=crimdata,its=its,model=ElectoralProxNoConCrim,rsq=FALSE)

moc.est <- list(apply(moc1,2,mean,na.rm=T),apply(moc2,2,mean,na.rm=T),
                apply(moc3,2,mean,na.rm=T),apply(moc4,2,mean,na.rm=T))
moc.sd <- list(apply(moc1,2,sd,na.rm=T),apply(moc2,2,sd,na.rm=T),
               apply(moc3,2,sd,na.rm=T),apply(moc4,2,sd,na.rm=T))

stargazer(
  ElectoralProxNoCon,ElectoralProxNoConEcon,ElectoralProxNoConEnv,ElectoralProxNoConCrim,
  font.size="footnotesize",model.numbers=F,
  column.sep.width="1pt",single.row=T,type="html",out="tableC7.htm",
  keep=c("opinion","treattwo","opinion:treattwo"),
  covariate.labels=c("Constituency Opinion","Two-Year","Const. Opinion * Two-Year"),
  coef=moc.est,se=moc.sd,p.auto=T,report=c("vcsp"),
  title="Electoral Proximity Effect (no controls)",
  dep.var.labels="Legislator Ideal Point",
  column.labels=c("All Votes","Economic","Environment","Crime"),
  omit.stat=c("F", "rsq","adj.rsq","ser")
)

## Table C.8

alldataideal <- data.frame(cbind(dataend2,allidealMCMC)) %>% select(num_range(prefix="X",range=1:500),treattwo,Republican,StateAbbr,Session) %>%
  melt(id.vars=c("treattwo","Republican","StateAbbr","Session"))
alldatamrp <- data.frame(cbind(dataend2,allmrpMCMC)) %>% select(num_range(prefix="X",range=1:500),treattwo,Republican,StateAbbr,Session) %>%
  melt(id.vars=c("treattwo","Republican","StateAbbr","Session"))
alldata <- data.frame(cbind(alldataideal,alldatamrp[,"value"]))
colnames(alldata) <- c("treattwo","Republican","StateAbbr","Session",
                       "It","ideal","opinion")

econdataideal <- data.frame(cbind(dataend2,econidealMCMC)) %>% select(num_range(prefix="X",range=1:500),treattwo,Republican,StateAbbr,Session) %>%
  melt(id.vars=c("treattwo","Republican","StateAbbr","Session"))
econdata <- data.frame(cbind(econdataideal,alldatamrp[,"value"]))
colnames(econdata) <- c("treattwo","Republican","StateAbbr","Session",
                        "It","ideal","opinion")

envdataideal <- data.frame(cbind(dataend2,envidealMCMC)) %>% select(num_range(prefix="X",range=1:500),treattwo,Republican,StateAbbr,Session) %>%
  melt(id.vars=c("treattwo","Republican","StateAbbr","Session"))
envdata <- data.frame(cbind(envdataideal,alldatamrp[,"value"]))
colnames(envdata) <- c("treattwo","Republican","StateAbbr","Session",
                       "It","ideal","opinion")

crimdataideal <- data.frame(cbind(dataend2,crimidealMCMC)) %>% select(num_range(prefix="X",range=1:500),treattwo,Republican,StateAbbr,Session) %>%
  melt(id.vars=c("treattwo","Republican","StateAbbr","Session"))
crimdata <- data.frame(cbind(crimdataideal,alldatamrp[,"value"]))
colnames(crimdata) <- c("treattwo","Republican","StateAbbr","Session",
                       "It","ideal","opinion")

alldata$It <- as.numeric(gsub("X","",alldata$It)) 
econdata$It <- as.numeric(gsub("X","",econdata$It)) 
envdata$It <- as.numeric(gsub("X","",envdata$It)) 
crimdata$It <- as.numeric(gsub("X","",crimdata$It)) 

its <- sort(sample(unique(alldata$It), min(500, length(unique(alldata$It)))))
ElectoralProxTW <- lm(ideal~opinion*treattwo+as.factor(Session)+StateAbbr+Republican,data=alldata[alldata$It==1,])
ElectoralProxTWEcon <- lm(ideal~opinion*treattwo+as.factor(Session)+StateAbbr+Republican,data=econdata[econdata$It==1,])
ElectoralProxTWEnv <- lm(ideal~opinion*treattwo+as.factor(Session)+StateAbbr+Republican,data=envdata[envdata$It==1,])
ElectoralProxTWCrim <- lm(ideal~opinion*treattwo+as.factor(Session)+StateAbbr+Republican,data=crimdata[crimdata$It==1,])
set.seed(401)
moc1 <- MOC(data=alldata,its=its,model=ElectoralProxTW,rsq=FALSE)
moc2 <- MOC(data=econdata,its=its,model=ElectoralProxTWEcon,rsq=FALSE)
moc3 <- MOC(data=envdata,its=its,model=ElectoralProxTWEnv,rsq=FALSE)
moc4 <- MOC(data=crimdata,its=its,model=ElectoralProxTWCrim,rsq=FALSE)

moc.est <- list(apply(moc1,2,mean,na.rm=T),apply(moc2,2,mean,na.rm=T),
                apply(moc3,2,mean,na.rm=T),apply(moc4,2,mean,na.rm=T))
moc.sd <- list(apply(moc1,2,sd,na.rm=T),apply(moc2,2,sd,na.rm=T),
               apply(moc3,2,sd,na.rm=T),apply(moc4,2,sd,na.rm=T))

stargazer(
  ElectoralProxTW,ElectoralProxTWEcon,ElectoralProxTWEnv,ElectoralProxTWCrim,
  font.size="footnotesize",model.numbers=F,
  column.sep.width="1pt",single.row=T,type="html",out="tableC8.htm",
  keep=c("opinion","treattwo","opinion:treattwo"),
  covariate.labels=c("Constituency Opinion","Two-Year","Const. Opinion * Two-Year"),
  coef=moc.est,se=moc.sd,p.auto=T,report=c("vcsp"),
  dep.var.labels="Legislator Ideal Point",
  title="Electoral Proximity Effect (using Tausanovitch and Warshaw 2013 scores)",
  column.labels=c("All Votes","Economic","Environment","Crime"),
  omit.stat=c("F", "rsq","adj.rsq","ser")
)

## Table C.9

alldata <- dataend2 %>% select(allidealNPAT,mrp_mean,treattwo,Republican,StateAbbr,Session)
colnames(alldata) <- c("ideal","opinion","treattwo","Republican","StateAbbr","Session")
econdata <- dataend2 %>% select(econidealNPAT,mrp_mean,treattwo,Republican,StateAbbr,Session)
colnames(econdata) <- c("ideal","opinion","treattwo","Republican","StateAbbr","Session")
envdata <- dataend2 %>% select(envidealNPAT,mrp_mean,treattwo,Republican,StateAbbr,Session)
colnames(envdata) <- c("ideal","opinion","treattwo","Republican","StateAbbr","Session")
crimdata <- dataend2 %>% select(crimidealNPAT,mrp_mean,treattwo,Republican,StateAbbr,Session)
colnames(crimdata) <- c("ideal","opinion","treattwo","Republican","StateAbbr","Session")

ElectoralProxNPAT <- lm(ideal~opinion*treattwo+Republican+StateAbbr+as.factor(Session),data=alldata)
ElectoralProxNPATEcon <- lm(ideal~opinion*treattwo+Republican+StateAbbr+as.factor(Session),data=econdata)
ElectoralProxNPATEnv <- lm(ideal~opinion*treattwo+Republican+StateAbbr+as.factor(Session),data=envdata)
ElectoralProxNPATCrim <- lm(ideal~opinion*treattwo+Republican+StateAbbr+as.factor(Session),data=crimdata)

stargazer(
  ElectoralProxNPAT,ElectoralProxNPATEcon,ElectoralProxNPATEnv,ElectoralProxNPATCrim,
  font.size="footnotesize",model.numbers=F,
  column.sep.width="1pt",single.row=T,type="html",out="tableC9.htm",
  keep=c("opinion","treattwo","opinion:treattwo"),
  covariate.labels=c("Constituency Opinion","Two-Year","Const. Opinion * Two-Year"),
  p.auto=T,report=c("vcsp"),
  dep.var.labels="Legislator Ideal Point",
  title="Electoral Proximity Effect (using NPAT surveys)",
  column.labels=c("All Votes","Economic","Environment","Crime"),
  omit.stat=c("F", "rsq","adj.rsq","ser")
)

## Table C.10

alldata <- dataend2 %>% select(allideal,mrp_mean,treattwo,Republican,StateAbbr,Session)
colnames(alldata) <- c("ideal","opinion","treattwo","Republican","StateAbbr","Session")
econdata <- dataend2 %>% select(econideal,econmrp_mean,treattwo,Republican,StateAbbr,Session)
colnames(econdata) <- c("ideal","opinion","treattwo","Republican","StateAbbr","Session")
envdata <- dataend2 %>% select(envideal,envmrp_mean,treattwo,Republican,StateAbbr,Session)
colnames(envdata) <- c("ideal","opinion","treattwo","Republican","StateAbbr","Session")
crimdata <- dataend2 %>% select(crimideal,crimmrp_mean,treattwo,Republican,StateAbbr,Session)
colnames(crimdata) <- c("ideal","opinion","treattwo","Republican","StateAbbr","Session")

ElectoralProxUnadjust <- lm(ideal~opinion*treattwo+Republican+StateAbbr+as.factor(Session),data=alldata)
ElectoralProxUnadjustEcon <- lm(ideal~opinion*treattwo+Republican+StateAbbr+as.factor(Session),data=econdata)
ElectoralProxUnadjustEnv <- lm(ideal~opinion*treattwo+Republican+StateAbbr+as.factor(Session),data=envdata)
ElectoralProxUnadjustCrim <- lm(ideal~opinion*treattwo+Republican+StateAbbr+as.factor(Session),data=crimdata)

stargazer(
  ElectoralProxUnadjust,ElectoralProxUnadjustEcon,ElectoralProxUnadjustEnv,ElectoralProxUnadjustCrim,
  font.size="footnotesize",model.numbers=F,
  column.sep.width="1pt",single.row=T,type="html",out="tableC10.htm",
  keep=c("opinion","treattwo","opinion:treattwo"),
  covariate.labels=c("Constituency Opinion","Two-Year","Const. Opinion * Two-Year"),
  p.auto=T,report=c("vcsp"),
  dep.var.labels="Legislator Ideal Point",
  title="Electoral Proximity Effect (using unadjusted estimates)",
  column.labels=c("All Votes","Economic","Environment","Crime"),
  omit.stat=c("F", "rsq","adj.rsq","ser")
)

## Table D.11

allidealMCMC <- read.csv("allidealMCMC.csv") %>% select(num_range(prefix="X",range=1:500))
econidealMCMC <- read.csv("econidealMCMC.csv") %>% select(num_range(prefix="X",range=1:500))
envidealMCMC <- read.csv("envidealMCMC.csv") %>% select(num_range(prefix="X",range=1:500))
crimidealMCMC <- read.csv("crimidealMCMC.csv") %>% select(num_range(prefix="X",range=1:500))
allmrpMCMC <- read.csv("allmrpMCMC.csv") %>% select(num_range(prefix="X",range=1:500))
econmrpMCMC <- read.csv("econmrpMCMC.csv") %>% select(num_range(prefix="X",range=1:500))
envmrpMCMC <- read.csv("envmrpMCMC.csv") %>% select(num_range(prefix="X",range=1:500))
crimmrpMCMC <- read.csv("crimmrpMCMC.csv") %>% select(num_range(prefix="X",range=1:500))

alldataideal <- data.frame(cbind(dataend2,allidealMCMC)) %>% select(num_range(prefix="X",range=1:500),treattwo,Republican,StateAbbr,Session,termlimit) %>%
  melt(id.vars=c("treattwo","Republican","StateAbbr","Session","termlimit"))
alldatamrp <- data.frame(cbind(dataend2,allmrpMCMC)) %>% select(num_range(prefix="X",range=1:500),treattwo,Republican,StateAbbr,Session,termlimit) %>%
  melt(id.vars=c("treattwo","Republican","StateAbbr","Session","termlimit"))
alldata <- data.frame(cbind(alldataideal,alldatamrp[,"value"]))
colnames(alldata) <- c("treattwo","Republican","StateAbbr","Session","termlimit",
                       "It","ideal","opinion")

econdataideal <- data.frame(cbind(dataend2,econidealMCMC)) %>% select(num_range(prefix="X",range=1:500),treattwo,Republican,StateAbbr,Session,termlimit) %>%
  melt(id.vars=c("treattwo","Republican","StateAbbr","Session","termlimit"))
econdatamrp <- data.frame(cbind(dataend2,econmrpMCMC)) %>% select(num_range(prefix="X",range=1:500),treattwo,Republican,StateAbbr,Session,termlimit) %>%
  melt(id.vars=c("treattwo","Republican","StateAbbr","Session","termlimit"))
econdata <- data.frame(cbind(econdataideal,econdatamrp[,"value"]))
colnames(econdata) <- c("treattwo","Republican","StateAbbr","Session","termlimit",
                        "It","ideal","opinion")

envdataideal <- data.frame(cbind(dataend2,envidealMCMC)) %>% select(num_range(prefix="X",range=1:500),treattwo,Republican,StateAbbr,Session,termlimit) %>%
  melt(id.vars=c("treattwo","Republican","StateAbbr","Session","termlimit"))
envdatamrp <- data.frame(cbind(dataend2,envmrpMCMC)) %>% select(num_range(prefix="X",range=1:500),treattwo,Republican,StateAbbr,Session,termlimit) %>%
  melt(id.vars=c("treattwo","Republican","StateAbbr","Session","termlimit"))
envdata <- data.frame(cbind(envdataideal,envdatamrp[,"value"]))
colnames(envdata) <- c("treattwo","Republican","StateAbbr","Session","termlimit",
                       "It","ideal","opinion")

crimdataideal <- data.frame(cbind(dataend2,crimidealMCMC)) %>% select(num_range(prefix="X",range=1:500),treattwo,Republican,StateAbbr,Session,termlimit) %>%
  melt(id.vars=c("treattwo","Republican","StateAbbr","Session","termlimit"))
crimdatamrp <- data.frame(cbind(dataend2,crimmrpMCMC)) %>% select(num_range(prefix="X",range=1:500),treattwo,Republican,StateAbbr,Session,termlimit) %>%
  melt(id.vars=c("treattwo","Republican","StateAbbr","Session","termlimit"))
crimdata <- data.frame(cbind(crimdataideal,crimdatamrp[,"value"]))
colnames(crimdata) <- c("treattwo","Republican","StateAbbr","Session","termlimit",
                       "It","ideal","opinion")

alldata$It <- as.numeric(gsub("X","",alldata$It)) 
econdata$It <- as.numeric(gsub("X","",econdata$It)) 
envdata$It <- as.numeric(gsub("X","",envdata$It))
crimdata$It <- as.numeric(gsub("X","",crimdata$It))

its <- sort(sample(unique(alldata$It), min(500, length(unique(alldata$It)))))
ElectoralProxContTL <- lm(ideal~opinion*treattwo+Republican+StateAbbr+as.factor(Session)+termlimit,data=alldata[alldata$It==1,])
ElectoralProxContTLEcon <- lm(ideal~opinion*treattwo+Republican+StateAbbr+as.factor(Session)+termlimit,data=econdata[econdata$It==1,])
ElectoralProxContTLEnv <- lm(ideal~opinion*treattwo+Republican+StateAbbr+as.factor(Session)+termlimit,data=envdata[envdata$It==1,])
ElectoralProxContTLCrim <- lm(ideal~opinion*treattwo+Republican+StateAbbr+as.factor(Session)+termlimit,data=crimdata[crimdata$It==1,])
set.seed(401)
moc1 <- MOC(data=alldata,its=its,model=ElectoralProxContTL,rsq=FALSE)
moc2 <- MOC(data=econdata,its=its,model=ElectoralProxContTLEcon,rsq=FALSE)
moc3 <- MOC(data=envdata,its=its,model=ElectoralProxContTLEnv,rsq=FALSE)
moc4 <- MOC(data=crimdata,its=its,model=ElectoralProxContTLCrim,rsq=FALSE)

moc.est <- list(apply(moc1,2,mean,na.rm=T),apply(moc2,2,mean,na.rm=T),
                apply(moc3,2,mean,na.rm=T),apply(moc4,2,mean,na.rm=T))
moc.sd <- list(apply(moc1,2,sd,na.rm=T),apply(moc2,2,sd,na.rm=T),
               apply(moc3,2,sd,na.rm=T),apply(moc4,2,sd,na.rm=T))

stargazer(
  ElectoralProxContTL,ElectoralProxContTLEcon,ElectoralProxContTLEnv,ElectoralProxContTLCrim,
  font.size="footnotesize",model.numbers=F,
  column.sep.width="1pt",single.row=T,type="html",out="tableD11.htm",
  keep=c("opinion","treattwo","opinion:treattwo"),
  covariate.labels=c("Constituency Opinion","Two-Year","Const. Opinion * Two-Year"),
  coef=moc.est,se=moc.sd,p.auto=T,report=c("vcsp"),
  title="Electoral Proximity Effect (controlling for term-limit status)",
  column.labels=c("All Votes","Economic","Environment","Crime"),
  dep.var.labels="Legislator Ideal Point",
  omit.stat=c("F", "rsq","adj.rsq","ser")## from standard normal (very close to t when DF = 3,500)
)

## Table D.12

ElectoralProxNoTL <- lm(ideal~opinion*treattwo+Republican+StateAbbr+as.factor(Session),data=alldata[alldata$It==1 & alldata$termlimit==0,])
ElectoralProxNoTLEcon <- lm(ideal~opinion*treattwo+Republican+StateAbbr+as.factor(Session),data=econdata[econdata$It==1 & econdata$termlimit==0,])
ElectoralProxNoTLEnv <- lm(ideal~opinion*treattwo+Republican+StateAbbr+as.factor(Session),data=envdata[envdata$It==1 & envdata$termlimit==0,])
ElectoralProxNoTLCrim <- lm(ideal~opinion*treattwo+Republican+StateAbbr+as.factor(Session),data=crimdata[crimdata$It==1 & crimdata$termlimit==0,])
set.seed(401)
moc1 <- MOC(data=alldata,its=its,model=ElectoralProxNoTL,rsq=FALSE)
moc2 <- MOC(data=econdata,its=its,model=ElectoralProxNoTLEcon,rsq=FALSE)
moc3 <- MOC(data=envdata,its=its,model=ElectoralProxNoTLEnv,rsq=FALSE)
moc4 <- MOC(data=crimdata,its=its,model=ElectoralProxNoTLCrim,rsq=FALSE)

moc.est <- list(apply(moc1,2,mean,na.rm=T),apply(moc2,2,mean,na.rm=T),
                apply(moc3,2,mean,na.rm=T),apply(moc4,2,mean,na.rm=T))
moc.sd <- list(apply(moc1,2,sd,na.rm=T),apply(moc2,2,sd,na.rm=T),
               apply(moc3,2,sd,na.rm=T),apply(moc4,2,sd,na.rm=T))

stargazer(
  ElectoralProxNoTL,ElectoralProxNoTLEcon,ElectoralProxNoTLEnv,ElectoralProxNoTLCrim,
  font.size="footnotesize",model.numbers=F,
  column.sep.width="1pt",single.row=T,type="html",out="tableD12.htm",
  keep=c("opinion","treattwo","opinion:treattwo"),
  covariate.labels=c("Constituency Opinion","Two-Year","Const. Opinion * Two-Year"),
  coef=moc.est,se=moc.sd,p.auto=T,report=c("vcsp"),
  title="Electoral Proximity Effect (no term-limited legislators)",
  column.labels=c("All Votes","Economic","Environment","Crime"),
  dep.var.labels="Legislator Ideal Point",
  omit.stat=c("F", "rsq","adj.rsq","ser")## from standard normal (very close to t when DF = 3,500)
)

# Table F.13

gaysuppopinion <- read.csv("IllinoisestimatesGayMarriageDisaggregated.csv")
colnames(gaysuppopinion)[which(colnames(gaysuppopinion)=="X")] <- "DistrictNumber"

dataIL <- dataend2[dataend2$StateAbbr=="IL" & dataend2$Session==2012,]
gaysuppdata <- merge(dataIL,gaysuppopinion,by="DistrictNumber")
gaysuppdata$vote <- ifelse(gaysuppdata$GaySupp==1,1,
                           ifelse(gaysuppdata$GaySupp==6,0,NA))
gaysuppdata$overall <- gaysuppdata$overall*100

gaysupp <- lm(vote~overall*treattwo,data=gaysuppdata)

penreformopinion <- read.csv("IllinoisestimatesPenReformDisaggregated.csv")
colnames(penreformopinion)[which(colnames(penreformopinion)=="X")] <- "DistrictNumber"

dataIL <- dataend2[dataend2$StateAbbr=="IL" & dataend2$Session==2012,]
penreformdata <- merge(dataIL,penreformopinion,by="DistrictNumber")
penreformdata$vote <- ifelse(penreformdata$PensionReform==1,1,
                             ifelse(penreformdata$PensionReform==6,0,NA))
penreformdata$overall <- penreformdata$overall*100

penreform <- lm(vote~overall*treattwo,data=penreformdata)

conccarryopinion <- read.csv("IllinoisestimatesConcealCarryDisaggregated.csv")
colnames(conccarryopinion)[which(colnames(conccarryopinion)=="X")] <- "DistrictNumber"

dataIL <- dataend2[dataend2$StateAbbr=="IL" & dataend2$Session==2012,]
conccarrydata <- merge(dataIL,conccarryopinion,by="DistrictNumber")
conccarrydata$vote <- ifelse(conccarrydata$ConcealCarry==1,1,
                             ifelse(conccarrydata$ConcealCarry==6,0,NA))
conccarrydata$overall <- conccarrydata$overall*100

conccarry <- lm(vote~overall*treattwo,data=conccarrydata)

stargazer(gaysupp,penreform,conccarry,
          font.size="footnotesize",
          model.numbers=F,
          column.sep.width = "2pt",single.row=T,type="html",out="tableF13.htm",
          keep=c("overall","treattwo","overall:treattwo"),
          covariate.labels=c("Constituency Opinion","Two-Year","Const. Opinion * Two-Year"),
          dep.var.labels="Vote in Favor",
          column.labels=c("Gay Marriage","Pension Reform",
                          "Concealed Carry"),
          report = ("vcsp"),
          title="Responsiveness on Specific Roll-Call Votes", 
          omit.stat=c("F", "rsq","adj.rsq","ser"),
          no.space=TRUE)

# Table F.14

medmjopinion <- read.csv("IllinoisestimatesMedMJDisaggregated.csv")
colnames(medmjopinion)[which(colnames(medmjopinion)=="X")] <- "DistrictNumber"

dataIL <- dataend2[dataend2$StateAbbr=="IL" & dataend2$Session==2012,]
medmjdata <- merge(dataIL,medmjopinion,by="DistrictNumber")
medmjdata$vote <- ifelse(medmjdata$MedMJ==1,1,
                         ifelse(medmjdata$MedMJ==6,0,NA))
medmjdata$overall <- medmjdata$overall*100

medmj <- lm(vote~overall*treattwo,data=medmjdata)

checksopinion <- read.csv("IllinoisestimatesBackgroundChecksDisaggregated.csv")
colnames(checksopinion)[which(colnames(checksopinion)=="X")] <- "DistrictNumber"

dataIL <- dataend2[dataend2$StateAbbr=="IL" & dataend2$Session==2012,]
checksdata <- merge(dataIL,checksopinion,by="DistrictNumber")
checksdata$vote <- ifelse(checksdata$Background==1,1,
                          ifelse(checksdata$Background==6,0,NA))
checksdata$overall <- checksdata$overall*100

checks <- lm(vote~overall*treattwo,data=checksdata)

cola25Kopinion <- read.csv("IllinoisestimatesCOLA25KDisaggregated.csv")
colnames(cola25Kopinion)[which(colnames(cola25Kopinion)=="X")] <- "DistrictNumber"

dataIL <- dataend2[dataend2$StateAbbr=="IL" & dataend2$Session==2012,]
cola25Kdata <- merge(dataIL,cola25Kopinion,by="DistrictNumber")
cola25Kdata$vote <- ifelse(cola25Kdata$COLA25K==1,1,
                          ifelse(cola25Kdata$COLA25K==6,0,NA))
cola25Kdata$overall <- cola25Kdata$overall*100

cola25K <- lm(vote~overall*treattwo,data=cola25Kdata)

stargazer(medmj,checks,cola25K,
          font.size="footnotesize",
          model.numbers=F,
          column.sep.width = "2pt",single.row=T,type="html",out="tableF14.htm",
          keep=c("overall","treattwo","overall:treattwo"),
          covariate.labels=c("Constituency Opinion","Two-Year","Const. Opinion * Two-Year"),
          dep.var.labels="Vote in Favor",
          column.labels=c("Medical Marijuana","Background Checks","COLA Incr."),
          title="Responsiveness on Specific Roll-Call Votes", 
          report = ("vcsp"),
          omit.stat=c("F", "rsq","adj.rsq","ser"),
          no.space=TRUE)

# Table F.15

gamblingopinion <- read.csv("IllinoisestimatesGamblingDisaggregated.csv")
colnames(gamblingopinion)[which(colnames(gamblingopinion)=="X")] <- "DistrictNumber"

dataIL <- dataend2[dataend2$StateAbbr=="IL" & dataend2$Session==2012,]
gamblingdata <- merge(dataIL,gamblingopinion,by="DistrictNumber")
gamblingdata$vote <- ifelse(gamblingdata$Gamble==1,1,
                            ifelse(gamblingdata$Gamble==6,0,NA))
gamblingdata$overall <- gamblingdata$overall*100

gambling <- lm(vote~overall*treattwo,data=gamblingdata)

ammoopinion <- read.csv("IllinoisestimatesAmmoDisaggregated.csv")
colnames(ammoopinion)[which(colnames(ammoopinion)=="X")] <- "DistrictNumber"

dataIL <- dataend2[dataend2$StateAbbr=="IL" & dataend2$Session==2012,]
ammodata <- merge(dataIL,ammoopinion,by="DistrictNumber")
ammodata$vote <- ifelse(ammodata$Ammo==1,1,
                        ifelse(ammodata$Ammo==6,0,NA))
ammodata$overall <- ammodata$overall*100

ammo <- lm(vote~overall*treattwo,data=ammodata)

stargazer(gambling,ammo,
          font.size="footnotesize",
          model.numbers=F,
          column.sep.width = "2pt",single.row=T,type="html",out="tableF15.htm",
          keep=c("overall","treattwo","overall:treattwo"),
          covariate.labels=c("Constituency Opinion","Two-Year","Const. Opinion * Two-Year"),
          dep.var.labels="Vote in Favor",
          column.labels=c("Gambling","Caps on Ammunition"),
          title="Responsiveness on Specific Roll-Call Votes", 
          report = ("vcsp"),
          omit.stat=c("F", "rsq","adj.rsq","ser"),
          no.space=TRUE)

## Figure F.13

dataIL <- dataend2[dataend2$StateAbbr=="IL" & dataend2$Session==2012,]
dataIL$condition <- as.factor(ifelse(dataIL$treattwo==1,"Two Years",
                                     "Four Years"))

gaysuppopinion <- read.csv("IllinoisestimatesGayMarriageMRP.csv")
colnames(gaysuppopinion)[which(colnames(gaysuppopinion)=="X")] <- "DistrictNumber"

gaysuppdata <- merge(dataIL,gaysuppopinion,by="DistrictNumber")
gaysuppdata$vote <- ifelse(gaysuppdata$GaySupp==1,1,
                           ifelse(gaysuppdata$GaySupp==6,0,NA))
gaysuppdata$overall <- gaysuppdata$mean*100
gaysuppdata$majsupport <- ifelse(gaysuppdata$overall>=50,1,0)
gaysuppdata$resp <- gaysuppdata$vote==gaysuppdata$majsupport

GaySupp <- lm(vote~overall*condition,data=gaysuppdata)

penreformopinion <- read.csv("IllinoisestimatesPenReformMRP.csv")
colnames(penreformopinion)[which(colnames(penreformopinion)=="X")] <- "DistrictNumber"

penreformdata <- merge(dataIL,penreformopinion,by="DistrictNumber")
penreformdata$vote <- ifelse(penreformdata$PensionReform==1,1,
                             ifelse(penreformdata$PensionReform==6,0,NA))
penreformdata$overall <- penreformdata$mean*100
penreformdata$majsupport <- ifelse(penreformdata$overall>=50,1,0)
penreformdata$resp <- penreformdata$vote==penreformdata$majsupport

PenReform <- lm(vote~overall*condition,data=penreformdata)

medmjopinion <- read.csv("IllinoisestimatesMedMJMRP.csv")
colnames(medmjopinion)[which(colnames(medmjopinion)=="X")] <- "DistrictNumber"

medmjdata <- merge(dataIL,medmjopinion,by="DistrictNumber")
medmjdata$vote <- ifelse(medmjdata$MedMJ==1,1,
                         ifelse(medmjdata$MedMJ==6,0,NA))
medmjdata$overall <- medmjdata$mean*100
medmjdata$majsupport <- ifelse(medmjdata$overall>=50,1,0)
medmjdata$resp <- medmjdata$vote==medmjdata$majsupport

MedMJ <- lm(vote~overall*condition,data=medmjdata)

conccarryopinion <- read.csv("IllinoisestimatesConcealCarryMRP.csv")
colnames(conccarryopinion)[which(colnames(conccarryopinion)=="X")] <- "DistrictNumber"

conccarrydata <- merge(dataIL,conccarryopinion,by="DistrictNumber")
conccarrydata$vote <- ifelse(conccarrydata$ConcealCarry==1,1,
                             ifelse(conccarrydata$ConcealCarry==6,0,NA))
conccarrydata$overall <- conccarrydata$mean*100
conccarrydata$majsupport <- ifelse(conccarrydata$overall>=50,1,0)
conccarrydata$resp <- conccarrydata$vote==conccarrydata$majsupport

ConcCarry <- lm(vote~overall*condition,data=conccarrydata)

gamblingopinion <- read.csv("IllinoisestimatesGambleMRP.csv")
colnames(gamblingopinion)[which(colnames(gamblingopinion)=="X")] <- "DistrictNumber"

gamblingdata <- merge(dataIL,gamblingopinion,by="DistrictNumber")
gamblingdata$vote <- ifelse(gamblingdata$Gamble==1,1,
                            ifelse(gamblingdata$Gamble==6,0,NA))
gamblingdata$overall <- gamblingdata$mean*100
gamblingdata$majsupport <- ifelse(gamblingdata$overall>=50,1,0)
gamblingdata$resp <- gamblingdata$vote==gamblingdata$majsupport

Gambling <- lm(vote~overall*condition,data=gamblingdata)

checksopinion <- read.csv("IllinoisestimatesBackgroundChecksMRP.csv")
colnames(checksopinion)[which(colnames(checksopinion)=="X")] <- "DistrictNumber"

checksdata <- merge(dataIL,checksopinion,by="DistrictNumber")
checksdata$vote <- ifelse(checksdata$Background==1,1,
                          ifelse(checksdata$Background==6,0,NA))
checksdata$overall <- checksdata$mean*100
checksdata$majsupport <- ifelse(checksdata$overall>=50,1,0)
checksdata$resp <- checksdata$vote==checksdata$majsupport

Checks <- lm(vote~overall*condition,data=checksdata)

cola25Kopinion <- read.csv("IllinoisestimatesCOLA25KMRP.csv")
colnames(cola25Kopinion)[which(colnames(cola25Kopinion)=="X")] <- "DistrictNumber"

cola25Kdata <- merge(dataIL,cola25Kopinion,by="DistrictNumber")
cola25Kdata$vote <- ifelse(cola25Kdata$COLA25K==1,1,
                           ifelse(cola25Kdata$COLA25K==6,0,NA))
cola25Kdata$overall <- cola25Kdata$mean*100
cola25Kdata$majsupport <- ifelse(cola25Kdata$overall>=50,1,0)
cola25Kdata$resp <- cola25Kdata$vote==cola25Kdata$majsupport

cola25K <- lm(vote~overall*condition,data=cola25Kdata)

ammoopinion <- read.csv("IllinoisestimatesAmmoMRP.csv")
colnames(ammoopinion)[which(colnames(ammoopinion)=="X")] <- "DistrictNumber"

ammodata <- merge(dataIL,ammoopinion,by="DistrictNumber")
ammodata$vote <- ifelse(ammodata$Ammo==1,1,
                        ifelse(ammodata$Ammo==6,0,NA))
ammodata$overall <- ammodata$mean*100
ammodata$majsupport <- ifelse(ammodata$overall>=50,1,0)
ammodata$resp <- ammodata$vote==ammodata$majsupport

ammo <- lm(vote~overall*condition,data=ammodata)

fulldata <- rbind(ammodata,checksdata,conccarrydata,gamblingdata,
                  gaysuppdata,medmjdata,penreformdata,cola25Kdata)
fulldata$issue <- c(rep(0,nrow(ammodata)),rep(1,nrow(checksdata)),
                    rep(2,nrow(conccarrydata)),rep(3,nrow(gamblingdata)),
                    rep(4,nrow(gaysuppdata)),rep(5,nrow(medmjdata)),
                    rep(6,nrow(penreformdata)),rep(7,nrow(cola25Kdata)))
fullreg <- lm(vote~overall*condition,data=fulldata)

ammoplot <- ggplot(ammodata,aes(y=vote,x=overall))+
  stat_smooth(method = "glm", 
              method.args = list(family = "binomial"), 
              se = FALSE,fullrange=T) +
  geom_point(size = 2)+
  theme_bw() +
  ylab("Legislator Vote") + 
  xlab("Constituency Support (Percentage)")+ 
  ggtitle("Caps on Ammunition")  +
  xlim(c(0,100))+ 
  scale_y_continuous(breaks=c(0,1),
                     labels=c("0","1"),
                     limits=c(0,1),
                     expand = c(0,0)) + 
  theme(plot.title = element_text(hjust = 0.5)) +
  theme(legend.position = "none")  

checksplot <- ggplot(checksdata,aes(y=vote,x=overall))+
  geom_point(size = 2)+
  stat_smooth(method = "glm", 
              method.args = list(family = "binomial"), 
              se = FALSE,fullrange=T) +
  theme_bw() +
  ylab("Legislator Vote") + 
  xlab("Constituency Support (Percentage)")+ 
  ggtitle("Background Checks")  +
  xlim(c(0,100))+ 
  scale_y_continuous(breaks=c(0,1),
                     labels=c("0","1"),
                     limits=c(0,1),
                     expand = c(0,0)) + 
  theme(plot.title = element_text(hjust = 0.5)) +
  theme(legend.position = "none")

gamblingplot <- ggplot(gamblingdata,aes(y=vote,x=overall))+
  geom_point(size = 2)+
  stat_smooth(method = "glm", 
              method.args = list(family = "binomial"), 
              se = FALSE,fullrange=T) +
  theme_bw() +
  ylab("Legislator Vote") + 
  xlab("Constituency Support (Percentage)")+ 
  ggtitle("Expanding Gambling")  +
  xlim(c(0,100))+ 
  scale_y_continuous(breaks=c(0,1),
                     labels=c("0","1"),
                     limits=c(0,1),
                     expand = c(0,0)) + 
  theme(plot.title = element_text(hjust = 0.5)) +
  theme(legend.position = "none")

medmjplot <- ggplot(medmjdata,aes(y=vote,x=overall))+
  geom_point(size = 2)+
  stat_smooth(method = "glm", 
              method.args = list(family = "binomial"), 
              se = FALSE,fullrange=T) +
  theme_bw() +
  ylab("Legislator Vote") + 
  xlab("Constituency Support (Percentage)")+ 
  ggtitle("Medical Marijuana")  +
  xlim(c(0,100))+ 
  scale_y_continuous(breaks=c(0,1),
                     labels=c("0","1"),
                     limits=c(0,1),
                     expand = c(0,0)) + 
  theme(plot.title = element_text(hjust = 0.5)) +
  theme(legend.position = "none")

penreformplot <- ggplot(penreformdata,aes(y=vote,x=overall))+
  geom_point(size = 2)+
  stat_smooth(method = "glm", 
              method.args = list(family = "binomial"), 
              se = FALSE,fullrange=T) +
  theme_bw() +
  ylab("Legislator Vote") + 
  xlab("Constituency Support (Percentage)")+ 
  ggtitle("Pension Reform")  +
  xlim(c(0,100))+ 
  scale_y_continuous(breaks=c(0,1),
                     labels=c("0","1"),
                     limits=c(0,1),
                     expand = c(0,0)) + 
  theme(plot.title = element_text(hjust = 0.5)) +
  theme(legend.position = "none")

cola25Kplot <- ggplot(cola25Kdata,aes(y=vote,x=overall))+
  geom_point(size = 2)+
  stat_smooth(method = "glm", 
              method.args = list(family = "binomial"), 
              se = FALSE,fullrange=T) +
  theme_bw() +
  ylab("Legislator Vote") + 
  xlab("Constituency Support (Percentage)")+ 
  ggtitle("COLA Incr.")  +
  xlim(c(0,100))+ 
  scale_y_continuous(breaks=c(0,1),
                     labels=c("0","1"),
                     limits=c(0,1),
                     expand = c(0,0)) + 
  theme(plot.title = element_text(hjust = 0.5)) +
  theme(legend.position = "none")

gaysuppplot <- ggplot(gaysuppdata,aes(y=vote,x=overall))+
  geom_point(size = 2)+
  stat_smooth(method = "glm", 
              method.args = list(family = "binomial"), 
              se = FALSE,fullrange=T) +
  theme_bw() +
  ylab("Legislator Vote") + 
  xlab("Constituency Support (Percentage)")+ 
  ggtitle("Legalizing Gay Marriage")  +
  xlim(c(0,100))+ 
  scale_y_continuous(breaks=c(0,1),
                     labels=c("0","1"),
                     limits=c(0,1),
                     expand = c(0,0)) + 
  theme(plot.title = element_text(hjust = 0.5)) +
  theme(legend.position = "none")

conccarryplot <- ggplot(conccarrydata,aes(y=vote,x=overall))+
  geom_point(size = 2)+
  stat_smooth(method = "glm", 
              method.args = list(family = "binomial"), 
              se = FALSE,fullrange=T) +
  theme_bw() +
  ylab("Legislator Vote") + 
  xlab("Constituency Support (Percentage)")+ 
  ggtitle("Concealed Carry")  +
  xlim(c(0,100))+ 
  scale_y_continuous(breaks=c(0,1),
                     labels=c("0","1"),
                     limits=c(0,1),
                     expand = c(0,0)) + 
  theme(plot.title = element_text(hjust = 0.5)) +
  theme(legend.position = "none")

ggarrange(ggarrange(ammoplot,NULL,checksplot,NULL,gamblingplot,nrow=1,ncol=5,
                    widths=c(1,0.25,1,0.25,1)),
          ggarrange(penreformplot,NULL,medmjplot,NULL,conccarryplot,nrow=1,ncol=5,
                    widths=c(1,0.25,1,0.25,1)),
          ggarrange(NULL,gaysuppplot,NULL,cola25Kplot,NULL,nrow=1,ncol=5,
                    widths=c(0.25,1,0.25,1,0.25)),
          nrow=3,ncol=1)

## Figure G.14

fullplot <- ggplot(fulldata, aes(x=overall/100)) +
  geom_density(fill="gray")+
  theme_bw()+
  labs(title="All Votes",x="Constituency Opinion", y = "Density")+
  theme(plot.title = element_text(hjust = 0.5)) +
  scale_x_continuous(limits = c(0,1.1), expand = c(0, 0)) +
  scale_y_continuous(limits = c(0,10), expand = c(0, 0)) 

ammoplot <- ggplot(ammodata, aes(x=overall/100)) +
  geom_density(fill="gray")+
  theme_bw()+
  labs(title="Ammunition Clips",x="Constituency Opinion", y = "Density")+
  theme(plot.title = element_text(hjust = 0.5)) +
  scale_x_continuous(limits = c(0,1.1), expand = c(0, 0)) +
  scale_y_continuous(limits = c(0,10), expand = c(0, 0)) 

checksplot <- ggplot(checksdata, aes(x=overall/100)) +
  geom_density(fill="gray")+
  theme_bw()+
  labs(title="Background Checks",x="Constituency Opinion", y = "Density")+
  theme(plot.title = element_text(hjust = 0.5)) +
  scale_x_continuous(limits = c(0,1.1), expand = c(0, 0)) +
  scale_y_continuous(limits = c(0, 20), expand = c(0, 0))

gambleplot <- ggplot(gamblingdata, aes(x=overall/100)) +
  geom_density(fill="gray")+
  theme_bw()+
  labs(title="Gambling",x="Constituency Opinion", y = "Density")+
  theme(plot.title = element_text(hjust = 0.5)) +
  scale_x_continuous(limits = c(0,1.1), expand = c(0, 0)) +
  scale_y_continuous(limits = c(0,10), expand = c(0, 0)) 

medmjplot <- ggplot(medmjdata, aes(x=overall/100)) +
  geom_density(fill="gray")+
  theme_bw()+
  labs(title="Med. Marijuana",x="Constituency Opinion", y = "Density")+
  theme(plot.title = element_text(hjust = 0.5)) +
  scale_x_continuous(limits = c(0,1.1), expand = c(0, 0)) +
  scale_y_continuous(limits = c(0,10), expand = c(0, 0)) 

penreformplot <- ggplot(penreformdata, aes(x=overall/100)) +
  geom_density(fill="gray")+
  theme_bw()+
  labs(title="Pen. Reform",x="Constituency Opinion", y = "Density")+
  theme(plot.title = element_text(hjust = 0.5)) +
  scale_x_continuous(limits = c(0,1.1), expand = c(0, 0)) +
  scale_y_continuous(limits = c(0,10), expand = c(0, 0)) 

cola25Kplot <- ggplot(cola25Kdata, aes(x=overall/100)) +
  geom_density(fill="gray")+
  theme_bw()+
  labs(title="COLA Incr.",x="Constituency Opinion", y = "Density")+
  theme(plot.title = element_text(hjust = 0.5)) +
  scale_x_continuous(limits = c(0,1.1), expand = c(0, 0)) +
  scale_y_continuous(limits = c(0,20), expand = c(0, 0)) 

gaysuppplot <- ggplot(gaysuppdata, aes(x=overall/100)) +
  geom_density(fill="gray")+
  theme_bw()+
  labs(x="Constituency Opinion", y = "Density")+
  ggtitle("Gay Marriage") + 
  theme(plot.title = element_text(hjust = 0.5)) +
  scale_x_continuous(limits = c(0,1.1), expand = c(0, 0)) +
  scale_y_continuous(limits = c(0,10), expand = c(0, 0)) 

conccarryplot <- ggplot(conccarrydata, aes(x=overall/100)) +
  geom_density(fill="gray")+
  theme_bw()+
  labs(x="Constituency Opinion", y = "Density")+
  ggtitle("Concealed Carry") + 
  theme(plot.title = element_text(hjust = 0.5)) +
  scale_x_continuous(limits = c(0,1.1), expand = c(0, 0)) +
  scale_y_continuous(limits = c(0,10), expand = c(0, 0)) 

ggarrange(ggarrange(fullplot, ammoplot,checksplot,nrow=1,ncol=3,
                    widths=c(1,1,1)),
          ggarrange(gambleplot,penreformplot,medmjplot,nrow=1,ncol=3,
                    widths=c(1,1,1)),
          ggarrange(conccarryplot,gaysuppplot,cola25Kplot,nrow=1,ncol=3,
                    widths=c(1,1,1)),
          nrow=3,ncol=1)

## Figure G.15

gaysuppresp <- gaysuppdata %>% select(num_range(prefix="X",range=1:500),treattwo,vote) %>%
  melt(id.vars=c("treattwo","vote"))
colnames(gaysuppresp) <- c("treattwo","vote","It","opinion")
gaysuppresp$resp <- ifelse(gaysuppresp$opinion>=0.5 & gaysuppresp$vote==1 | 
                             gaysuppresp$opinion<0.5 & gaysuppresp$vote==0,1,0)
gaysuppresp$It <- as.numeric(gsub("X","",gaysuppresp$It))
penrefresp <- penreformdata %>% select(num_range(prefix="X",range=1:500),treattwo,vote) %>%
  melt(id.vars=c("treattwo","vote"))
colnames(penrefresp) <- c("treattwo","vote","It","opinion")
penrefresp$resp <- ifelse(penrefresp$opinion>=0.5 & penrefresp$vote==1 | 
                             penrefresp$opinion<0.5 & penrefresp$vote==0,1,0)
penrefresp$It <- as.numeric(gsub("X","",penrefresp$It))
medmjresp <- medmjdata %>% select(num_range(prefix="X",range=1:500),treattwo,vote) %>%
  melt(id.vars=c("treattwo","vote"))
colnames(medmjresp) <- c("treattwo","vote","It","opinion")
medmjresp$resp <- ifelse(medmjresp$opinion>=0.5 & medmjresp$vote==1 | 
                            medmjresp$opinion<0.5 & medmjresp$vote==0,1,0)
medmjresp$It <- as.numeric(gsub("X","",medmjresp$It))
conccarryresp <- conccarrydata %>% select(num_range(prefix="X",range=1:500),treattwo,vote) %>%
  melt(id.vars=c("treattwo","vote"))
colnames(conccarryresp) <- c("treattwo","vote","It","opinion")
conccarryresp$resp <- ifelse(conccarryresp$opinion>=0.5 & conccarryresp$vote==1 | 
                               conccarryresp$opinion<0.5 & conccarryresp$vote==0,1,0)
conccarryresp$It <- as.numeric(gsub("X","",conccarryresp$It))
gamblingresp <- gamblingdata %>% select(num_range(prefix="X",range=1:500),treattwo,vote) %>%
  melt(id.vars=c("treattwo","vote"))
colnames(gamblingresp) <- c("treattwo","vote","It","opinion")
gamblingresp$resp <- ifelse(gamblingresp$opinion>=0.5 & gamblingresp$vote==1 | 
                              gamblingresp$opinion<0.5 & gamblingresp$vote==0,1,0)
gamblingresp$It <- as.numeric(gsub("X","",gamblingresp$It))
checksresp <- checksdata %>% select(num_range(prefix="X",range=1:500),treattwo,vote) %>%
  melt(id.vars=c("treattwo","vote"))
colnames(checksresp) <- c("treattwo","vote","It","opinion")
checksresp$resp <- ifelse(checksresp$opinion>=0.5 & checksresp$vote==1 | 
                            checksresp$opinion<0.5 & checksresp$vote==0,1,0)
checksresp$It <- as.numeric(gsub("X","",checksresp$It))
cola25Kresp <- cola25Kdata %>% select(num_range(prefix="X",range=1:500),treattwo,vote) %>%
  melt(id.vars=c("treattwo","vote"))
colnames(cola25Kresp) <- c("treattwo","vote","It","opinion")
cola25Kresp$resp <- ifelse(cola25Kresp$opinion>=0.5 & cola25Kresp$vote==1 | 
                             cola25Kresp$opinion<0.5 & cola25Kresp$vote==0,1,0)
cola25Kresp$It <- as.numeric(gsub("X","",cola25Kresp$It))
ammoresp <- ammodata %>% select(num_range(prefix="X",range=1:500),treattwo,vote) %>%
  melt(id.vars=c("treattwo","vote"))
colnames(ammoresp) <- c("treattwo","vote","It","opinion")
ammoresp$resp <- ifelse(ammoresp$opinion>=0.5 & ammoresp$vote==1 | 
                          ammoresp$opinion<0.5 & ammoresp$vote==0,1,0)
ammoresp$It <- as.numeric(gsub("X","",ammoresp$It))

GaySupp <- lm(resp~treattwo,data=gaysuppresp[gaysuppresp$It==1,])
PenReform <- lm(resp~treattwo,data=penrefresp[penrefresp$It==1,])
MedMJ <- lm(resp~treattwo,data=medmjresp[medmjresp$It==1,])
ConcCarry <- lm(resp~treattwo,data=conccarryresp[conccarryresp$It==1,])
Gambling <- lm(resp~treattwo,data=gamblingresp[gamblingresp$It==1,])
Checks <- lm(resp~treattwo,data=checksresp[checksresp$It==1,])
cola25K <- lm(resp~treattwo,data=cola25Kresp[cola25Kresp$It==1,])
ammo <- lm(resp~treattwo,data=ammoresp[ammoresp$It==1,])
fulldata <- rbind(ammoresp,checksresp,conccarryresp,gamblingresp,
                  gaysuppresp,medmjresp,penrefresp,cola25Kresp)
fulldata$issue <- c(rep(0,nrow(ammoresp)),rep(1,nrow(checksresp)),
                    rep(2,nrow(conccarryresp)),rep(3,nrow(gamblingresp)),
                    rep(4,nrow(gaysuppresp)),rep(5,nrow(medmjresp)),
                    rep(6,nrow(penrefresp)),rep(7,nrow(cola25Kresp)))
fullreg <- lm(resp~treattwo+as.factor(issue),data=fulldata)

its <- 1:500
set.seed(401)
moc1 <- MOC(data=gaysuppresp,its=its,model=GaySupp,rsq=FALSE)
moc2 <- MOC(data=penrefresp,its=its,model=PenReform,rsq=FALSE)
moc3 <- MOC(data=medmjresp,its=its,model=MedMJ,rsq=FALSE)
moc4 <- MOC(data=conccarryresp,its=its,model=ConcCarry,rsq=FALSE)
moc5 <- MOC(data=gamblingresp,its=its,model=Gambling,rsq=FALSE)
moc6 <- MOC(data=checksresp,its=its,model=Checks,rsq=FALSE)
moc7 <- MOC(data=cola25Kresp,its=its,model=cola25K,rsq=FALSE)
moc8 <- MOC(data=ammoresp,its=its,model=ammo,rsq=FALSE)
moc9 <- MOC(data=fulldata,its=its,model=fullreg,rsq=FALSE)
moc.est <- list(apply(moc1,2,mean,na.rm=T)[c("treattwo")],
                apply(moc2,2,mean,na.rm=T)[c("treattwo")],
                apply(moc3,2,mean,na.rm=T)[c("treattwo")],
                apply(moc4,2,mean,na.rm=T)[c("treattwo")],
                apply(moc5,2,mean,na.rm=T)[c("treattwo")],
                 apply(moc6,2,mean,na.rm=T)[c("treattwo")],
                 apply(moc7,2,mean,na.rm=T)[c("treattwo")],
                 apply(moc8,2,mean,na.rm=T)[c("treattwo")],
                 apply(moc9,2,mean,na.rm=T)[c("treattwo")])
moc.sd <- list(apply(moc1,2,sd,na.rm=T)[c("treattwo")],
                apply(moc2,2,sd,na.rm=T)[c("treattwo")],
                apply(moc3,2,sd,na.rm=T)[c("treattwo")],
                apply(moc4,2,sd,na.rm=T)[c("treattwo")],
                apply(moc5,2,sd,na.rm=T)[c("treattwo")],
                apply(moc6,2,sd,na.rm=T)[c("treattwo")],
                apply(moc7,2,sd,na.rm=T)[c("treattwo")],
                apply(moc8,2,sd,na.rm=T)[c("treattwo")],
                apply(moc9,2,sd,na.rm=T)[c("treattwo")])

term <- c("All \nVotes", "Gay \nMarriage", "Pen. \nReform", "Background \nChecks",
          "Ammunition \nClips","Gambling","Med. \nMarijuana","COLA Incr.",
          "Concealed \nCarry")
estimate <- c(moc.est[[9]],moc.est[[1]],moc.est[[2]],moc.est[[6]],moc.est[[8]],
              moc.est[[5]],moc.est[[3]],moc.est[[7]],moc.est[[4]])
std.error <- c(moc.sd[[9]],moc.sd[[1]],moc.sd[[2]],moc.sd[[6]],moc.sd[[8]],
               moc.sd[[5]],moc.sd[[3]],moc.sd[[7]],moc.sd[[4]])
pvalues <- round(2*pnorm(-abs(estimate/std.error)),3)
pvalues <- ifelse(pvalues==0,paste("p < 0.001"),paste("p=",pvalues,sep=""))
dfplot <- data.frame(term, estimate, std.error)
png("FigureG15.png",width=1200,res=250,height=750)
theme_set(theme_bw())
dwplot(dfplot) +
  geom_vline(aes(x=0), lty=2, xintercept=0) +
  ylab('Roll-Call Votes') + 
  xlab('Effect') + 
  xlim(c(-0.6,0.7))+
  geom_text(x=0.65,y=1,label=paste(pvalues[9],sep=""),fontface=6)+
  geom_text(x=0.65,y=2,label=paste(pvalues[8],sep=""),fontface=6)+
  geom_text(x=0.65,y=3,label=paste(pvalues[7],sep=""),fontface=6)+
  geom_text(x=0.65,y=4,label=paste(pvalues[6],sep=""),fontface=6)+
  geom_text(x=0.65,y=5,label=paste(pvalues[5],sep=""),fontface=6)+
  geom_text(x=0.65,y=6,label=paste(pvalues[4],sep=""),fontface=6)+
  geom_text(x=0.65,y=7,label=paste(pvalues[3],sep=""),fontface=6)+
  geom_text(x=0.65,y=8,label=paste(pvalues[2],sep=""),fontface=6)+
  geom_text(x=0.65,y=9,label=paste(pvalues[1],sep=""),fontface=6)+
  scale_y_discrete(name = 'Roll-Call Votes') +
  theme(plot.title = element_text(face="bold",hjust=0.5))
dev.off()

## Table G.16

congruence <- round(c(mean(fulldata$resp,na.rm=T),mean(ammodata$resp,na.rm=T),
                      mean(checksdata$resp,na.rm=T),mean(conccarrydata$resp,na.rm=T),
                      mean(gamblingdata$resp,na.rm=T),mean(gaysuppdata$resp,na.rm=T),
                      mean(medmjdata$resp,na.rm=T),mean(penreformdata$resp,na.rm=T),
                      mean(cola25Kdata$resp,na.rm=T)),2)
diffeffects <- c(paste(round(moc.est[[9]],2)," (SE=",round(moc.sd[[9]],2),",",pvalues[1],")",sep=""),
                 paste(round(moc.est[[8]],2)," (SE=",round(moc.sd[[8]],2),",",pvalues[5],")",sep=""),
                 paste(round(moc.est[[6]],2)," (SE=",round(moc.sd[[6]],3),",",pvalues[4],")",sep=""),
                 paste(round(moc.est[[4]],2)," (SE=",round(moc.sd[[4]],2),",",pvalues[9],")",sep=""),
                 paste(round(moc.est[[5]],2)," (SE=",round(moc.sd[[5]],2),",",pvalues[6],")",sep=""),
                 paste(round(moc.est[[1]],2)," (SE=",round(moc.sd[[1]],2),",",pvalues[2],")",sep=""),
                 paste(round(moc.est[[3]],2)," (SE=",round(moc.sd[[3]],2),",",pvalues[7],")",sep=""),
                 paste(round(moc.est[[2]],2)," (SE=",round(moc.sd[[2]],2),",",pvalues[3],")",sep=""),
                 paste(round(moc.est[[7]],2)," (SE=",round(moc.sd[[7]],2),",",pvalues[8],")",sep=""))
varnames <- c("All Votes","Ammunition Clips","Background Checks","Concealed Carry",
              "Gambling","Gay Marriage","Med. Marijuana","Pen. Reform",
              "COLA Incr.")

sumstattable <- data.frame(cbind(varnames,congruence,diffeffects))
colnames(sumstattable) <- c("Roll-Call Vote","Congruence","Difference Between Two and Four Years")
rownames(sumstattable) <- NULL


Summarytable <- formattable(sumstattable, 
                            align =c("l","c","c","c","c"), 
                            list(`Variable Name` = formatter(
                              "span", style = ~ style(color = "grey",font.weight = "bold")) 
                            ))
#png("SummaryStatistics.png")
Summarytable
#dev.off()

## Table G.17

fulldata <- rbind(ammodata,checksdata,conccarrydata,gamblingdata,
                  gaysuppdata,medmjdata,penreformdata,cola25Kdata)
fulldata$issue <- c(rep(0,nrow(ammodata)),rep(1,nrow(checksdata)),
                    rep(2,nrow(conccarrydata)),rep(3,nrow(gamblingdata)),
                    rep(4,nrow(gaysuppdata)),rep(5,nrow(medmjdata)),
                    rep(6,nrow(penreformdata)),rep(7,nrow(cola25Kdata)))
fullreg <- lm(vote~overall*condition,data=fulldata)

fullcrosstab <- data.frame(round(c(mean(fulldata$vote==0 & fulldata$majsupport==1,na.rm=T),
                                   mean(fulldata$vote==0 & fulldata$majsupport==0,na.rm=T)),2),
                           round(c(mean(fulldata$vote==1 & fulldata$majsupport==1,na.rm=T),
                                   mean(fulldata$vote==1 & fulldata$majsupport==0,na.rm=T)),2))
ammocrosstab <- data.frame(round(c(mean(ammodata$vote==0 & ammodata$majsupport==1,na.rm=T),
                                   mean(ammodata$vote==0 & ammodata$majsupport==0,na.rm=T)),2),
                           round(c(mean(ammodata$vote==1 & ammodata$majsupport==1,na.rm=T),
                                   mean(ammodata$vote==1 & ammodata$majsupport==0,na.rm=T)),2))
checkscrosstab <- data.frame(round(c(mean(checksdata$vote==0 & checksdata$majsupport==1,na.rm=T),
                                     mean(checksdata$vote==0 & checksdata$majsupport==0,na.rm=T)),2),
                             round(c(mean(checksdata$vote==1 & checksdata$majsupport==1,na.rm=T),
                                     mean(checksdata$vote==1 & checksdata$majsupport==0,na.rm=T)),2))
conccarrycrosstab <- data.frame(round(c(mean(conccarrydata$vote==0 & conccarrydata$majsupport==1,na.rm=T),
                                        mean(conccarrydata$vote==0 & conccarrydata$majsupport==0,na.rm=T)),2),
                                round(c(mean(conccarrydata$vote==1 & conccarrydata$majsupport==1,na.rm=T),
                                        mean(conccarrydata$vote==1 & conccarrydata$majsupport==0,na.rm=T)),2))
gamblingcrosstab <- data.frame(round(c(mean(gamblingdata$vote==0 & gamblingdata$majsupport==1,na.rm=T),
                                       mean(gamblingdata$vote==0 & gamblingdata$majsupport==0,na.rm=T)),2),
                               round(c(mean(gamblingdata$vote==1 & gamblingdata$majsupport==1,na.rm=T),
                                       mean(gamblingdata$vote==1 & gamblingdata$majsupport==0,na.rm=T)),2))
gaysuppcrosstab <- data.frame(round(c(mean(gaysuppdata$vote==0 & gaysuppdata$majsupport==1,na.rm=T),
                                      mean(gaysuppdata$vote==0 & gaysuppdata$majsupport==0,na.rm=T)),2),
                              round(c(mean(gaysuppdata$vote==1 & gaysuppdata$majsupport==1,na.rm=T),
                                      mean(gaysuppdata$vote==1 & gaysuppdata$majsupport==0,na.rm=T)),2))
medmjcrosstab <- data.frame(round(c(mean(medmjdata$vote==0 & medmjdata$majsupport==1,na.rm=T),
                                    mean(medmjdata$vote==0 & medmjdata$majsupport==0,na.rm=T)),2),
                            round(c(mean(medmjdata$vote==1 & medmjdata$majsupport==1,na.rm=T),
                                    mean(medmjdata$vote==1 & medmjdata$majsupport==0,na.rm=T)),2))
penreformcrosstab <- data.frame(round(c(mean(penreformdata$vote==0 & penreformdata$majsupport==1,na.rm=T),
                                        mean(penreformdata$vote==0 & penreformdata$majsupport==0,na.rm=T)),2),
                                round(c(mean(penreformdata$vote==1 & penreformdata$majsupport==1,na.rm=T),
                                        mean(penreformdata$vote==1 & penreformdata$majsupport==0,na.rm=T)),2))
cola25Kcrosstab <- data.frame(round(c(mean(cola25Kdata$vote==0 & cola25Kdata$majsupport==1,na.rm=T),
                                      mean(cola25Kdata$vote==0 & cola25Kdata$majsupport==0,na.rm=T)),2),
                              round(c(mean(cola25Kdata$vote==1 & cola25Kdata$majsupport==1,na.rm=T),
                                      mean(cola25Kdata$vote==1 & cola25Kdata$majsupport==0,na.rm=T)),2))
colnames(fullcrosstab) <- colnames(ammocrosstab) <- colnames(checkscrosstab) <- colnames(conccarrycrosstab) <- colnames(gamblingcrosstab) <- colnames(gaysuppcrosstab) <- colnames(medmjcrosstab) <- colnames(penreformcrosstab) <- colnames(cola25Kcrosstab) <- c("Oppose","Favor")
rownames(fullcrosstab) <- rownames(ammocrosstab) <- rownames(checkscrosstab) <- rownames(conccarrycrosstab) <- rownames(gamblingcrosstab) <- rownames(gaysuppcrosstab) <- rownames(medmjcrosstab) <- rownames(penreformcrosstab) <- rownames(cola25Kcrosstab) <- c("Favor","Oppose")

add_title <- function(g, title, padding = unit(2,"mm"), lpos=1, ...){
  tg <- textGrob(title, ...)
  g %>%
    gtable::gtable_add_rows(heights = grobHeight(tg) + padding, pos = 0L) %>% 
    gtable::gtable_add_grob(tg, t=1,b=1,l=lpos,r=ncol(g))
  
}

grid.arrange(tableGrob(fullcrosstab) %>% add_title('All Votes', gp=gpar(fontsize=10, fontface=4), hjust=0, x=0, lpos=2),
             tableGrob(ammocrosstab) %>% add_title('Ammo Clips', gp=gpar(fontsize=10, fontface=4), hjust=0, x=0, lpos=2),
             tableGrob(checkscrosstab) %>% add_title('Background Checks', gp=gpar(fontsize=10, fontface=4), hjust=0, x=0, lpos=2),
             tableGrob(conccarrycrosstab) %>% add_title('Conc. Carry', gp=gpar(fontsize=10, fontface=4), hjust=0, x=0, lpos=2),
             tableGrob(gamblingcrosstab) %>% add_title('Gambling', gp=gpar(fontsize=10, fontface=4), hjust=0, x=0, lpos=2),
             tableGrob(gaysuppcrosstab) %>% add_title('Gay Marriage', gp=gpar(fontsize=10, fontface=4), hjust=0, x=0, lpos=2),
             tableGrob(medmjcrosstab) %>% add_title('Med. Marijuana', gp=gpar(fontsize=10, fontface=4), hjust=0, x=0, lpos=2),
             tableGrob(penreformcrosstab) %>% add_title('Pen. Reform', gp=gpar(fontsize=10, fontface=4), hjust=0, x=0, lpos=2),
             tableGrob(cola25Kcrosstab) %>% add_title('COLA Incr.', gp=gpar(fontsize=10, fontface=4), hjust=0, x=0, lpos=2),
             nrow=3,ncol=3,left="District Median",top="Legislator Votes")


